﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using System.Diagnostics;

namespace Legend.IO
{
    /// <summary>
    /// Provides extension methods for the Stream-class.
    /// </summary>
    public static class StreamExtensions
    {
        /// <summary>
        /// Reads the content of the stream to a byte array, starting
        /// from the current position of the stream.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="bufferSize">The size of the buffer used when reading.</param>
        /// <returns>The bytes read from the stream.</returns>
        public static byte[] ReadToEnd(this Stream stream, int bufferSize)
        {
            Require.ThatArgument(stream).Named("stream").IsNotNull();
            Require.ThatArgument(bufferSize).Named("bufferSize").IsInRange(1, int.MaxValue);
            
            byte[] buffer = new byte[bufferSize];

            int totalNumberOfBytesRead = 0;
            bool done = false;

            while (!done)
            {
                // Expand array if there's not enough room left for one
                // read.
                if (totalNumberOfBytesRead + bufferSize > buffer.Length)
                {
                    byte[] resizedBuffer = new byte[buffer.Length * 2];
                    Buffer.BlockCopy(buffer, 0, resizedBuffer, 0, buffer.Length);
                    buffer = resizedBuffer;
                }

                var bytesReadInChunk = stream.Read(buffer, totalNumberOfBytesRead, bufferSize);
                totalNumberOfBytesRead += bytesReadInChunk;

                // We're done if no more bytes were read.
                done = bytesReadInChunk == 0;
            }

            if (totalNumberOfBytesRead != buffer.Length)
            {
                byte[] resizedBuffer = new byte[totalNumberOfBytesRead];
                Buffer.BlockCopy(buffer, 0, resizedBuffer, 0, totalNumberOfBytesRead);
                buffer = resizedBuffer;
                FileInfo f = null;
                DirectoryInfo d = null;
                
            }

            return buffer;
        }
    }
    
}
